import React, { Component } from 'react';
import {
    DeviceEventEmitter, View, AppState, Alert, BackHandler
} from 'react-native';
import PageStart from './containers/PageStart'
// import PageStart from './page/PageStart';
import JPushUtil from './utils/JPush';
import AppUpdatePage from './components/update/AppUpdatePage';
import AppUpdate from './components/update/AppUpdate';
import StorageHelper from './utils/storageHelper';
import Dictionary from './utils/dictionary';
import HotUpdate from './components/update/HotUpdate';
import HotUpdatePage from './components/update/HotUpdatePage';
import { STORAGE_CONSTANT } from './config/storage';
import CodePush from "react-native-code-push";
import BackgroundJob from 'react-native-background-job';
import { GLOBAL } from "./config/global";
import WS from "./utils/websocket";

//日期全局设置中文
import { LocaleConfig } from 'react-native-calendars';
LocaleConfig.locales['zh-Hans'] = {
    monthNames: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
    monthNamesShort: ['一', '二', '三', '四', '五', '六', '七', '八', '九', '十', '十一', '十二'],
    dayNamesShort: ['日', '一', '二', '三', '四', '五', '六'],
};
LocaleConfig.defaultLocale = 'zh-Hans';

class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            initRouteScreen: '',
            versionInfo: null,
            showAppUpdate: false,
            showHotUpdate: false,
            downloadProgress: {}
        }
        this.checkingAppUpdate = false;
        this.checkingHotUpdate = false;
        this.timer = null;
    }


    async componentWillMount() {
        BackgroundJob.register({
            jobKey: "掌上化销后台运行",
            job: () => console.log("掌上化销后台运行")
        });

        JPushUtil.listener();
        HotUpdate.getCurrentPackage().then(updateInfo => {
            if (updateInfo && updateInfo.label) {
                StorageHelper.set(STORAGE_CONSTANT.APP_HOT_VERSION, updateInfo.label);
            } else {
                StorageHelper.remove(STORAGE_CONSTANT.APP_HOT_VERSION);
            }
        })
        if (GLOBAL.TOKEN) {
            WS.createWebSocket();
        }
    }

    componentDidMount() {
        JPushUtil.setJPushModule();
        AppState.addEventListener('change', this._handleAppStateChange);
        this.listener = DeviceEventEmitter.addListener('checkUpdate', async () => {
            this.checkingAppUpdate = false;
            this.checkingHotUpdate = false;
            this.checkAppUpdate();
        });
    }

    componentWillUnmount() {
        AppState.removeEventListener('change', this._handleAppStateChange);
        this.listener.remove();
        this.timer && clearTimeout(this.timer);
    }

    // 监听是否切换到后台
    _handleAppStateChange = async (nextAppState) => {
        GLOBAL.APP_STATE = nextAppState;
        if (nextAppState == 'active') {
            this.checkingAppUpdate = false;
            this.checkingHotUpdate = false;
            this.checkAppUpdate();
            console.log("GLOBAL.TOKEN", GLOBAL.TOKEN)
            if (GLOBAL.TOKEN) {
                WS.createWebSocket();
            }
        } else if (nextAppState == 'background') {
            if (WS && WS.wsObj) {
                WS.wsObj.close();
            }
        }
    }

    // 检查版本更新
    async checkAppUpdate() {
        if (this.checkingAppUpdate) return;
        this.checkingAppUpdate = true;
        let versionInfo = await AppUpdate.checkUpdate();
        this.checkingAppUpdate = false;
        if (versionInfo) {
            this.setState({ versionInfo: versionInfo, showAppUpdate: !!versionInfo, showHotUpdate: false });
        } else {
            if (__DEV__) return;
            this.checkHotUpdate();
        }
    }

    downloadProgressCallback = (downloadProgress) => {
        this.setState({
            downloadProgress
        })
    }

    // 检查热更新
    async checkHotUpdate() {
        if (this.checkingHotUpdate) return;
        this.checkingHotUpdate = true;
        let updateInfo = await HotUpdate.checkUpdate();
        if (updateInfo.update) {
            this.setState({ showHotUpdate: true, showAppUpdate: false }, async () => {
                const { syncStatus } = await HotUpdate.doUpdate(this.downloadProgressCallback);
                if (syncStatus === 1) {
                    await Dictionary.updated(); // 热更成功 更新数据字典
                    this.setState({ showHotUpdate: false }, async () => {
                        this.timer = setTimeout(() => {
                            HotUpdate.restart();
                        }, 500)
                    })
                } else {
                    this.setState({ showHotUpdate: false });
                }
            })
        } else {
            this.checkingHotUpdate = false;
            HotUpdate.getCurrentPackage().then(updateInfo => {
                (updateInfo && updateInfo.label) && StorageHelper.set(STORAGE_CONSTANT.APP_HOT_VERSION, updateInfo.label);
            })
        }
    }


    render() {
        let { versionInfo, showAppUpdate, showHotUpdate, downloadProgress } = this.state;
        return (
            <View style={{ flex: 1 }}>
                {showHotUpdate ? <HotUpdatePage isVisible={showHotUpdate} downloadProgress={downloadProgress} /> : null}
                {showAppUpdate ? <AppUpdatePage versionInfo={versionInfo} isVisible={showAppUpdate} ignore={() => this.setState({ showAppUpdate: false })} /> : null}
                <PageStart />
            </View>
        );
    }


}

let codePushOptions = { checkFrequency: CodePush.CheckFrequency.MANUAL };

App = CodePush(codePushOptions)(App);

export default App;